﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Net.Http.Json;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Config;
using IMClient.Model;
using IMClient.Model.DTO;
using IMClient.Model.Message;
using IMClient.Model.UI;
using IMClient.WebSocketService;

namespace IMClient.ViewModels
{
    public partial class FriendNotificationViewModel : ObservableObject
    {
        private readonly HttpClient _httpClient;

        [ObservableProperty] private ObservableCollection<FriendNotification> notificationList = new();

        public FriendNotificationViewModel()
        {
            _httpClient = new HttpClient();
            WebSocketConnection.OnMessageReceived += OnMessageReceived;
        }

        private void OnMessageReceived(BaseMessage message)
        {
            if (message is AddFriendRequest friendRequest)
            {
                Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    NotificationList.Insert(0, new FriendNotification
                    {
                        Name = friendRequest.SenderName,
                        Avatar = friendRequest.SenderAvatar,
                        SenderId = friendRequest.SenderId,
                        Action = "请求加为好友",
                        Time = DateTime.Now.ToString("yyyy/MM/dd"),
                        Message = $"留言：{friendRequest.Description}",
                        Status = "待处理",
                        RequestMessageId = friendRequest.MessageId
                    });
                });
            }
            else if (message is AddFriendResponse friendResponse)
            {
                // 处理好友请求响应
                Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    var notification = NotificationList.FirstOrDefault(n =>
                        n.SenderId == friendResponse.SenderId);

                    if (notification != null)
                    {
                        notification.Status = friendResponse.Accepted ? "对方已同意" : "对方已拒绝";

                        if (friendResponse.Accepted)
                        {
                            ChatWindowViewModel.Instance.GetContactsViewModel()?.AddFriendAccept(
                                User.UserId ?? throw new InvalidOperationException(),
                                new FriendViewModel
                                {
                                    Id = notification.SenderId ??
                                               throw new InvalidOperationException("SenderId为空"),
                                    Name = notification.Name ?? throw new InvalidOperationException("Name为空"),
                                    Avatar = notification.Avatar ?? throw new InvalidOperationException("Avatar为空"),
                                    IsFriend = true
                                });
                        }
                    }
                });
            }
        }

        [RelayCommand]
        private async Task AcceptFriendRequest(FriendNotification notification)
        {
            await HandleFriendRequest(notification, true);
        }

        [RelayCommand]
        private async Task RejectFriendRequest(FriendNotification notification)
        {
            await HandleFriendRequest(notification, false);
        }

        private async Task HandleFriendRequest(FriendNotification notification, bool accept)
        {
            try
            {
                // 构造请求体
                var response = new AddFriendResponse
                {
                    SenderId = User.UserId ?? throw new InvalidOperationException("UserId为空"),
                    SenderName = User.UserName ?? throw new InvalidOperationException("UserName为空"),
                    ReceiverId = notification.SenderId ?? throw new InvalidOperationException("SenderId为空"),
                    Accepted = accept,
                    Content = accept ? $"{User.UserName} 同意了您的好友请求" : $"{User.UserName} 拒绝了您的好友请求",
                    RequestMessageId = notification.RequestMessageId
                };

                // 发送HTTP POST请求
                var httpResponse = await _httpClient.PostAsJsonAsync(
                    $"{NetWorkConfig.BaseUrl}/friend/response",
                    response
                );

                if (httpResponse.IsSuccessStatusCode)
                {
                    // 更新UI状态
                    notification.Status = accept ? "已同意" : "已拒绝";

                    // 如果接受请求且成功，触发好友列表刷新
                    if (accept)
                    {
                        ChatWindowViewModel.Instance.GetContactsViewModel()?.AddFriendAccept(User.UserId,
                            new FriendViewModel
                            {
                                Id = notification.SenderId,
                                Name = notification.Name ?? throw new InvalidOperationException("Name为空"),
                                Avatar = notification.Avatar ?? throw new InvalidOperationException("Avatar为空"),
                                IsFriend = true
                            });
                    }
                }
                else
                {
                    var error = await httpResponse.Content.ReadFromJsonAsync<ErrorResponse>();
                    throw new Exception(error?.Message ?? "处理好友请求失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理好友请求失败：{ex.Message}");
                // 可能需要回滚UI状态
                notification.Status = "待处理";
            }
        }
        // 将主动请求添加好友通知视图
        public void AddFriendRequest(FriendNotification notification)
        {
            NotificationList.Insert(0, notification);
        }
    }
}